<?php

namespace App\Service\Third;

use AlibabaCloud\Client\Request\Request;
use App\Constants\ErrorCode;
use App\Helpers\OcpcUtil;
use App\Model\Ocpc\OcpcBaidu;
use App\Model\Ocpc\OcpcBaiduLog;
use App\Model\Ocpc\OcpcBaiduLoseLog;
use App\Model\Ocpc\OcpcBaiduUser;
use App\Model\User;
use App\Service\BaseService;

/**
 * 百度推广回调 账号2
 */
class BaiduExtraAccountService extends BaseService
{
    public $info = '';
    public $eventType;
    /**
     * https://xxx.com/callback/baidu_extra_account?biz_type=feed&mac_md5=__MAC_MD5__&oaid=__OAID__&oaid_md5=__OAID_MD5__&mac1=__MAC__&imei_md5=__IMEI_MD5__&os=__OS__&ip=__IP__&ua=__UA__&android_id=__ANDROIDID__&ts=__TS__&userid=__USER_ID__&pid=__PLAN_ID__&uid=__UNIT_ID__&aid=__IDEA_ID__&click_id=__CLICK_ID__&size=__SIZE__&callback_url=__CALLBACK_URL__&sign=__SIGN__
     */
    public function handle()
    {
        $params = $this->request->all();
        log_info('baidu回调参数'.json_encode($params));
        $bizType = $params['biz_type'] == 'dasou' ? 2 : 1;
        $oaid = $params['oaid'] ?? '00000000';
        $channel = $params['channel'] ?? OcpcBaidu::CHANNELS[0];
        $forcedRecord = false;
        if ($oaid != "NULL" && substr($oaid, 0, 8) != "00000000") {
            $check = OcpcBaidu::existsOaid($oaid, $channel);
            if ($check) return 1;
        } else {
            $forcedRecord = true;
        }
        $params['akeys'] = config('ocpc.channel.408.akey1','NDM5NTQ3MDE=');
        $ret = OcpcBaidu::addLog($params, $bizType);
        log_info(__CLASS__ . "==Ret:{$ret}==Params:" . json_encode($params));
        if($ret && $forcedRecord){
            $record=[
                'ocpc_id'=>$ret,
                'channel'=>$channel,
                'akeys' =>$params['akeys'],
                'status'=>0,
                'callback_url' => $params['callback_url'] ?? '',
                'created_at'=>date('Y-m-d H:i:s'),
                'updated_at'=>date('Y-m-d H:i:s'),
            ];
            OcpcBaiduLoseLog::insert($record);
        }
        return $ret;
    }


    /**
     * 首次进行baidu渠道用户关联
     * @return false|mixed
     */
    private function relationBaiduAndUser($info)
    {
        $log = OcpcBaidu::handleSearch($info);
        if (!$log) {
            //从缺失oaid中获取一条
            $log = OcpcBaiduLoseLog::shift($info['channel']);
            if (!$log) {
                log_info(__CLASS__ . "==getBaiduOcpc==" . json_encode($info) . "===false");
                return false;
            }
        }
        $_insert = [
            'user_id' => $info['user_id'],
            'ocpc_id' => $log['id'],
            'url' => $log['callback_url'],
            'channel' => $log['channel'],
            'akeys' => $log['akeys'],
        ];
        OcpcBaiduUser::addRelation($_insert); //回传信息与用户进行关联
        return $log;
    }
}